package com.ogj.utils;

import com.ogj.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HtmlParseUtils {

    public List<Content> parseJDKey(String keywords) throws IOException {
        //获取请求 https://search.jd.com/Search?keyword=Java
        //前提 需要联网，不能使用ajax
        String url = "https://search.jd.com/Search?keyword="+keywords+"&enc=utf-8";
        //解析网页 Jsoup返回的Document就是Document对象
        Document document = Jsoup.parse(new URL(url), 30000);
        //所有在JS中使用的方法 都能用
        Element element = document.getElementById("J_goodsList");
//                System.out.println(element.html());
        //获取所有的li标签
        Elements elements = element.getElementsByTag("li");
        ArrayList<Content> goodsList = new ArrayList<>();
        //获取元素中的内容
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            String shop = el.getElementsByClass("curr-shop").eq(0).attr("title");
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            content.setShop(shop);

            goodsList.add(content);
        }
        System.out.println("====查找了===");
        return goodsList;
    }

//    public static void main(String[] args) throws IOException {
//        new HtmlParseUtils().parseJDKey("文法").forEach(System.out::println);
//    }

}
